package cn.simple.manager.scheduling;

import cn.simple.manager.Repository.BannerResponsitory;
import cn.simple.manager.todo.BannerStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import weixin.popular.api.MaterialAPI;
import weixin.popular.bean.material.MaterialBatchgetResult;
import weixin.popular.bean.material.MaterialBatchgetResultItemContent;
import weixin.popular.bean.material.MaterialcountResult;
import weixin.popular.bean.message.Article;
import weixin.popular.support.TokenManager;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
public class WechatNewsTaskSpider {
    @Value("${wechat.newsCount}")
    private int newsCount;


    @Autowired
    BannerResponsitory bannerResponsitory;
    //每隔2秒执行一次
    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(fixedRate = 30000)
    public void testTasks() {
        try {
            String token = TokenManager.getDefaultToken();
            MaterialcountResult materialcountResult = MaterialAPI.get_materialcount(token);
            int news_count = materialcountResult.getNews_count();
            int offset = news_count-(newsCount+1);
            if(offset<0){
                offset=0;
            }
            log.info("微信拉取素材 offset:"+offset+"\t count:"+newsCount);
            MaterialBatchgetResult materialBatchgetResult = MaterialAPI.batchget_material(token,"news",offset,newsCount);
            List<BannerStorage> bannerStorageList =  materialBatchgetResult.getItem().stream().map(item->{
                MaterialBatchgetResultItemContent materialBatchgetResultItemContent = item.getContent();
                List<Article> itemContent = materialBatchgetResultItemContent.getNews_item();
                Date update_date = Date.from(Instant.ofEpochSecond(Long.parseLong(item.getUpdate_time())));
                BannerStorage bannerStorage = new BannerStorage();
                bannerStorage.setId(UUID.randomUUID().toString());
                bannerStorage.setMediaId(item.getMedia_id());
                bannerStorage.setCreateTime(new Date());
                bannerStorage.setType("Wechat_news");
                bannerStorage.setUrl( itemContent.get(0).getUrl());
                bannerStorage.setTitle(itemContent.get(0).getTitle());
                bannerStorage.setUpdateTime(update_date);
                bannerStorage.setUpdateCount(0);
                bannerStorage.setThumbUrl(itemContent.get(0).getThumb_url());
                return bannerStorage;
            }).collect(Collectors.toList());

            List<String> mediaids = bannerStorageList.stream().map(b->b.getMediaId()).collect(Collectors.toList());
            List<BannerStorage> bannerStorages = bannerResponsitory.ListfindAllByMediaid(mediaids);
            checkWechatNewsUpdate(bannerStorages,bannerStorageList);
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    public void checkWechatNewsUpdate(List<BannerStorage> storages, List<BannerStorage> weChatNewsStorages){
        List<BannerStorage> UpdateList =new ArrayList<>();
        List<BannerStorage> addList = new ArrayList<>();
        for(BannerStorage weChatNewsStorage: weChatNewsStorages){
            if(storages.size()==0){
                addList.add(weChatNewsStorage);
            }
            for(BannerStorage storage:storages){
                if(weChatNewsStorage.getMediaId().equals(storage.getMediaId())){
                    if(weChatNewsStorage.getUpdateTime().getTime()>storage.getUpdateTime().getTime()){
                        weChatNewsStorage.setId(storage.getId());
                        weChatNewsStorage.setUpdateCount(storage.getUpdateCount()+1);
                        UpdateList.add(weChatNewsStorage);
                    }
                    //更新
                }else {
                    //新增
                    addList.add(weChatNewsStorage);
                }
            }
        }
        if(UpdateList.size()>0){
            log.error("批量更新");
        }
        if(addList.size()>0){
            bannerResponsitory.saveAll(addList);
            log.error("新增微信文章 "+addList.size()+" 条");
        }
    }
}
